import 'package:fish_redux/fish_redux.dart';
import 'package:kunlun_gas/AppViews/EngineerOrderView/model/normal_config_model.dart';
import 'dart:convert' as convert;
import 'action.dart';
import 'state.dart';
import '../../OrderView/model/order_view_model.dart';
import '../../../app_files.dart';
import 'dart:io';

Effect<PatrolOrderResultViewState> buildEffect() {
  return combineEffects(<Object, Effect<PatrolOrderResultViewState>>{
    PatrolOrderResultViewAction.onTapAddPic: _onTapAddPic,
    PatrolOrderResultViewAction.onTapPic: _onTapPic,
    PatrolOrderResultViewAction.onTapFixPic: _onTapFixPic,
    PatrolOrderResultViewAction.onTapAddFixPic: _onTapAddFixPic,
    PatrolOrderResultViewAction.onSubmit: _onSubmit,
    PatrolOrderResultViewAction.onTapSign: _onTapSign,
    PatrolOrderResultViewAction.onTapResultPic: _onTapResultPic,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<PatrolOrderResultViewState> ctx) async {
  if (!ctx.state.isDetail) {
    for (OrderConfigModel model in ctx.state.items) {
      if (!model.isNormal && !model.isNoneNormal) {
        ctx.state.isNormal = false;
        break;
      }
    }
    if (ctx.state.isNormal) ctx.state.orderStatus = 1;
    ctx.dispatch(PatrolOrderResultViewActionCreator.onAction());
  } else {
    ResultData res =
        await CommonNetWork.patrolOrderDetail(ctx.state.pointInfo.orderID);
    ctx.dispatch(
        PatrolOrderResultViewActionCreator.onGetData(res.data['data']));
  }
}

void _onTapAddPic(
    Action action, Context<PatrolOrderResultViewState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 1, info: ctx.state.pointInfo);
  if (imgFile != null) {
    ctx.dispatch(PatrolOrderResultViewActionCreator.setOrderPhoto(imgFile));
  }
}

void _onTapAddFixPic(
    Action action, Context<PatrolOrderResultViewState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 1, info: ctx.state.pointInfo);
  if (imgFile != null) {
    ctx.dispatch(PatrolOrderResultViewActionCreator.setFixPhoto(imgFile));
  }
}

void _onTapPic(Action action, Context<PatrolOrderResultViewState> ctx) async {
  pushPhoto(file) async {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex:ctx.state.orderPhoto.indexOf(file),
      files:ctx.state.orderPhoto,
    );
  }

  var file = action.payload;
  if (ctx.state.isDetail) {
    pushPhoto(file);
  } else {
    int res =
    await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.orderPhoto.remove(file);
      ctx.dispatch(PatrolOrderResultViewActionCreator.onAction());
    } else if (res == 0) {
      pushPhoto(file);
    }
  }
}

void _onTapFixPic(
    Action action, Context<PatrolOrderResultViewState> ctx) async {
  pushPhoto(file) async {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex:ctx.state.repairPhotos.indexOf(file),
      files:ctx.state.repairPhotos,
    );
  }

  var file = action.payload;
  if (ctx.state.isDetail) {
    pushPhoto(file);
  } else {
    int res =
    await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.repairPhotos.remove(file);
      ctx.dispatch(PatrolOrderResultViewActionCreator.onAction());
    } else if (res == 0) {
      pushPhoto(file);
    }
  }
}

void _onSubmit(Action action, Context<PatrolOrderResultViewState> ctx) async {
  if (ctx.state.orderSignPhoto == null) {
    var res = await CommonUtils.pushRoute(ctx.context, RoutePath.orderSignView);
    if (res != null) {
      ctx.state.orderSignPhoto = res;
      ctx.dispatch(PatrolOrderResultViewActionCreator.onAction());
    }
  } else {
    if (ctx.state.orderStatus == null) {
      CommonUtils.showErrorInfo(ctx.context, '请选择订单状态');
      return;
    }
    if (ctx.state.orderPhoto.length == 0) {
      CommonUtils.showErrorInfo(ctx.context, '请拍照留存');
      return;
    }
    List<String> contentPhoto = [];
    CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');
    List items = ctx.state.items.map((e) => e.toJson()).toList();
    for (var item in items) {
      List imgList = item['ImageList'];
      if (imgList != null) {
        List<String> uploads = await CommonNetWork.multiUploadImgs(imgList,
            userNo: ctx.state.pointInfo.pointID);
        item['ImageList'] = uploads;
        contentPhoto.addAll(uploads);
      }
    }
    String json = convert.jsonEncode(items);
//    print(json);

    List img = [];
    img.addAll(ctx.state.orderPhoto);
    img.add(ctx.state.orderSignPhoto);
    List<String> images = await CommonNetWork.multiUploadImgs(img,
        userNo: ctx.state.pointInfo.pointID);
    List<String> orderPhoto = images.sublist(0, images.length - 1);
    Navigator.pop(ctx.context);
    CommonUtils.showWaitLoading(ctx.context, descText: '正在提交中');
    List<String> repairPhotos = [];
    if (ctx.state.repairPhotos.isNotEmpty) {
      repairPhotos = await CommonNetWork.multiUploadImgs(ctx.state.repairPhotos,
          userNo: ctx.state.pointInfo.pointID);
    }

    ResultData res = await CommonNetWork.addPatrolOrder(
        orderPhoto: orderPhoto.join(','),
        infoJson: json,
        orderSign: images.last,
        orderStatus: ctx.state.orderStatus,
        orderID: ctx.state.pointInfo.orderID,
        fixContent: convert.jsonEncode(
            {'RepairContent': ctx.state.selfFixContentController.text}),
        fixPhoto: repairPhotos.join(','));
    Navigator.pop(ctx.context);
    if (res.success) {
      if (ctx.state.orderStatus == 2) {}

      bus.emit('refreshList');
      await CommonUtils.showAlertView(ctx.context, '成功提交工单');

//      int res = await CommonUtils.showOKCanceltView(ctx.context, '提交成功,是否分享安检结果？');
      Navigator.popUntil(ctx.context, (r) {
        CupertinoPageRoute route = r;
        return route.settings.name == RoutePath.patrolOrderListView;
      });
//      if (res == 1) {
//        CommonUtils.pushRoute(
//            ctx.context, RoutePath.orderResultEditView,
//            arguments: {
//              'info': ctx.state.userInfo,
//              'items': ctx.state.items
//            });
//      }
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
  }
}

void _onTapSign(Action action, Context<PatrolOrderResultViewState> ctx) async {
  if (ctx.state.isDetail) {
    List<GalleryExampleItem> items = [
      GalleryExampleItem(
        id: '0',
        resource: ctx.state.orderSignPhoto,
      )
    ];
    items = await CommonUtils.showPhotoAlbumView(
      ctx.context,
      initialIndex: 0,
      galleryItems: items,
    );
  } else {
    var res = await CommonUtils.showActionSheet(ctx.context, button: ['修改']);
    if (res == 0) {
      var file =
      await CommonUtils.pushRoute(ctx.context, RoutePath.orderSignView);
      if (file != null) {
        ctx.state.orderSignPhoto = file;
        ctx.dispatch(PatrolOrderResultViewActionCreator.onAction());
      }
    }
  }
}

void _onTapResultPic(
    Action action, Context<PatrolOrderResultViewState> ctx) async {
  NormalConfigModel model = action.payload['model'];
  var file = action.payload['data'];
  await CommonUtils.showMediaAlbumView(
    ctx.context,
    initialIndex: model.imageList.indexOf(file),
    files: model.imageList,
  );
}
